package com.sbtr.business.feature.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sbtr.business.feature.entity.FePcaRule;
import com.sbtr.business.feature.dto.FePcaRuleDto;

import com.sbtr.business.feature.service.FePcaRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbtr.business.feature.mapper.FePcaRuleMapper;
import com.sbtr.business.trainingserver.entity.TrainingServer;
import com.sbtr.business.trainingserver.service.impl.TrainingServerServiceImpl;
import com.sbtr.open.trainingserver.dto.TrainingServerDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sbtr.common.PageDto;
import com.sbtr.util.PageDtoUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主成分分析规则字段列表 Service接口实现类
 *
 * @author dgl
 * @since  2023-05-08
 */
@Transactional
@Service
public class FePcaRuleServiceImpl extends ServiceImpl<FePcaRuleMapper,FePcaRule> implements FePcaRuleService {

    @Autowired
    FePcaRuleMapper fePcaRuleMapper;


    @Autowired
    private TrainingServerServiceImpl serverService;
    @Autowired
    private RestTemplate restTemplate;

    private Logger logger = LoggerFactory.getLogger(FePcaRuleServiceImpl.class);

    @Override
    public PageDto<FePcaRule> pageList(FePcaRuleDto fePcaRuleDto) {

        IPage<FePcaRule> page = new Page<>();
        page.setSize(fePcaRuleDto.getPageSize());
        page.setCurrent(fePcaRuleDto.getPage());
        page = fePcaRuleMapper.selectPages(page, BeanUtil.beanToMap(fePcaRuleDto));
        PageDto<FePcaRule> r = PageDtoUtils.getPageDtoByIPage(page, FePcaRule.class);

        return r;
    }

    /**
     * 调用Python端的（模型训练服务）进行计算PCA结果
     * @param list
     * @param cum_var
     * @param trainServerIpId
     * @return
     */
    @Override
    public String exePythonPCA(List<List<String>> list, String cum_var, String trainServerIpId){
        // 根据训练任务id找出任务所在的训练服务器(训练任务分配表)
        TrainingServer trainingServer = serverService.getById(trainServerIpId);
        if (trainingServer == null || TrainingServerDto.TRAINING_SERVER_STATUS_OFFLINE.equals(trainingServer.getStatus())) {
            logger.warn("id为[{}]的算法服务器不存在或已下线", trainServerIpId);
            return "error";
        }
        // 向此训练服务器发送停止任务,调用算法训练端ip/pca接口
        String url = "http://" + trainingServer.getIp() + "/pca";
        HttpHeaders headers = this.initRestTemplateHeader();
        // 请求体
        Map<String, Object> postParameters = new HashMap<>();
        postParameters.put("dataArr", list);
        postParameters.put("cum_var", cum_var);
        String jsonBody = JSON.toJSONString(postParameters);
        HttpEntity<String> r = new HttpEntity<>(jsonBody, headers);
        ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, r, String.class);

        // 返回结果
        String body = postForEntity.getBody();
        JSONObject jsObj = JSONObject.parseObject(body);
        if (jsObj.getInteger("ret") != null && 0 == jsObj.getInteger("ret")) {
            System.err.println("--------true-----------");
            return jsObj.toJSONString();
        } else {
            System.err.println("--------false-----------");
            Integer ret = jsObj.getInteger("ret") != null ? jsObj.getInteger("ret") : 0;
            String msg = StringUtils.isNotBlank(jsObj.getString("msg")) ? jsObj.getString("msg") : "";
            logger.error("状态码: {},msg:{}", ret, msg);
        }
        return "";
    }

    /**
     * 初始化请求头 设置请求类型和接收类型
     *
     * @return
     */
    private HttpHeaders initRestTemplateHeader() {

        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);// 请求类型
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());// 接收类型
        return headers;
    }
}

